package com.wwwarehouse.taskcenter.fragment.job_point.step2.parent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.DimensionBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.constant.job_point.TaskCenterCommon;
import com.wwwarehouse.taskcenter.custom_view.NewLineFlexLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_BUSINESS_ID;
import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_JOB_POINT_UKID;
import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_WAREHOUSE_NAME;
import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_WAREHOUSE_UKID;
import static com.wwwarehouse.taskcenter.fragment.job_point.step2.child.ChildJobPointDimensionListFragment.KEY_DIMENSION_DETAILS;

/**
 * Created by Jackie on 2017/10/27
 * 父作业点位置维度
 */

public class ChangeTypeParentPositionFragment extends BaseFragment implements View.OnClickListener {
    private View mRootView;

    private NewLineFlexLayout mEndNewLineLayout;

    private LinearLayout mEndDetailsLayout;

    private Button mEndDetailsBtn;
    private Button mEndResetBtn;

    private Button mStartBtn;
    private ImageView mEndImg;

    private RelativeLayout mSaveLayout;
    private Button mSaveBtn;

    private String mBusinessId;
    private String mJobPointUkid;
    private String mWarehouseUkid;
    private String mWarehouseName;
    private DimensionBean mDimensionBean;

    private ChangeTypeParentPositionReceiver mReceiver;

    private static final int REQUEST_SAVE_DIMENSION = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_change_type_parent_position, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mActivity.unregisterReceiver(mReceiver);
    }

    private void initView() {
        mEndNewLineLayout = findView(mRootView, R.id.flex_layout_end);

        mEndDetailsLayout = findView(mRootView, R.id.ll_details_end);

        mStartBtn = findView(mRootView, R.id.btn_start);
        mEndImg = findView(mRootView, R.id.iv_plus_end);

        mEndDetailsBtn = findView(mRootView, R.id.btn_details_end);
        mEndResetBtn = findView(mRootView, R.id.btn_reset_end);

        mSaveLayout = findView(mRootView, R.id.rl_save);
        mSaveBtn = findView(mRootView, R.id.btn_save);
    }

    private void initData() {
        TaskCenterCommon.getInstance().setStart(false);
        TaskCenterCommon.getInstance().setDetails(false);
        TaskCenterCommon.getInstance().setStartMap(null);
        TaskCenterCommon.getInstance().setEndMap(null);

        Bundle bundle = getArguments();

        if (bundle != null) {
            mBusinessId = bundle.getString(KEY_BUSINESS_ID);
            mJobPointUkid = bundle.getString(KEY_JOB_POINT_UKID);
            mWarehouseUkid = bundle.getString(KEY_WAREHOUSE_UKID);
            mWarehouseName = bundle.getString(KEY_WAREHOUSE_NAME);

            mStartBtn.setText(mWarehouseName);

            mDimensionBean = (DimensionBean) bundle.getSerializable(KEY_DIMENSION_DETAILS);

            buildEchoMap(mDimensionBean);
            showEchoInfo(mDimensionBean);
        }
    }

    private void initEvent() {
        mEndImg.setOnClickListener(this);

        mEndDetailsBtn.setOnClickListener(this);
        mEndResetBtn.setOnClickListener(this);

        mSaveBtn.setOnClickListener(this);

        mReceiver = new ChangeTypeParentPositionReceiver();
        mActivity.registerReceiver(mReceiver, new IntentFilter("ChooseAddWayParentPositionByAny"));
        mActivity.registerReceiver(mReceiver, new IntentFilter("ChooseAddWayParentPositionByWarehousePoint"));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.iv_plus_end) {
            TaskCenterCommon.getInstance().setStart(false);
            TaskCenterCommon.getInstance().setDetails(false);

            Bundle bundle = new Bundle();
            bundle.putString(KEY_BUSINESS_ID, mBusinessId);
            bundle.putString(KEY_WAREHOUSE_UKID, mWarehouseUkid);

            ChooseAddWayParentPositionFragment chooseAddWayParentPositionFragment = new ChooseAddWayParentPositionFragment();
            chooseAddWayParentPositionFragment.setArguments(bundle);
            pushFragment(chooseAddWayParentPositionFragment);
        } else if (id == R.id.btn_details_end) {
            TaskCenterCommon.getInstance().setStart(false);
            TaskCenterCommon.getInstance().setDetails(true);

            Bundle bundle = new Bundle();
            bundle.putString(KEY_BUSINESS_ID, mBusinessId);
            bundle.putString(KEY_WAREHOUSE_UKID, mWarehouseUkid);

            ChooseAddWayParentPositionByWarehousePointFragment chooseAddWayParentPositionByWarehousePointFragment = new ChooseAddWayParentPositionByWarehousePointFragment();
            chooseAddWayParentPositionByWarehousePointFragment.setArguments(bundle);
            pushFragment(chooseAddWayParentPositionByWarehousePointFragment);
        } else if (id == R.id.btn_reset_end) {
            mEndNewLineLayout.removeAllViews();

            mEndImg.setVisibility(View.VISIBLE);
            mEndDetailsLayout.setVisibility(View.GONE);
            mSaveLayout.setVisibility(View.GONE);
        } else if (id == R.id.btn_save) {
            savePositionDimension();
        }

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChangeTypeParentPositionFragment) {
            mActivity.setTitle(R.string.change_dimension);
        }
    }

    @Override
    public void requestDatas() {

    }

    private void savePositionDimension() {
        showProgressDialog(getString(R.string.saving));

        Map map = new HashMap();

        map.put("dimensionType", "position");

        map.put("start", TaskCenterCommon.getInstance().getStartMap());
        map.put("end", TaskCenterCommon.getInstance().getEndMap());

        map.put("jobPointUkid", mJobPointUkid);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_SAVE_DIMENSION, map, mOnResponseListener, REQUEST_SAVE_DIMENSION);
    }

    /**
     * 显示回显信息
     * @param dimensionBean
     */
    private void buildEchoMap(DimensionBean dimensionBean) {
        if (dimensionBean.getStart() != null) {
            Map startMap = new HashMap();
            List<Map<String, String>> startList = new ArrayList<>();

            for (DimensionBean.StartBean.ListBean listBean : dimensionBean.getStart().getList()) {
                Map<String, String> listMap = new HashMap<>();

                listMap.put("key", listBean.getKey());
                listMap.put("value", listBean.getValue());

                startList.add(listMap);
            }

            startMap.put("list", startList);
            startMap.put("type", dimensionBean.getStart().getType());

            TaskCenterCommon.getInstance().setStartMap(startMap);
        }

        if (dimensionBean.getEnd() != null) {
            Map endMap = new HashMap();
            List<Map<String, String>> endList = new ArrayList<>();

            for (DimensionBean.EndBean.ListBean listBean : dimensionBean.getEnd().getList()) {
                Map<String, String> listMap = new HashMap<>();

                listMap.put("key", listBean.getKey());
                listMap.put("value", listBean.getValue());

                endList.add(listMap);
            }

            endMap.put("list", endList);
            endMap.put("type", dimensionBean.getEnd().getType());

            TaskCenterCommon.getInstance().setEndMap(endMap);
        }
    }

    private void showEchoInfo(DimensionBean dimensionBean) {
        if (dimensionBean.getStart() != null) {
            if ("CONSTANT".equals(dimensionBean.getStart().getType())) {

            } else {

            }
        }

        if (dimensionBean.getEnd() != null) {
            if ("CONSTANT".equals(dimensionBean.getEnd().getType())) {
                //常量
                mEndNewLineLayout.removeAllViews();

                mEndImg.setVisibility(View.GONE);
                mEndDetailsLayout.setVisibility(View.GONE);

                for (DimensionBean.EndBean.ListBean listBean : dimensionBean.getEnd().getList()) {
                    StateButton stateButton = new StateButton(mActivity);
                    stateButton.setRound(true);
                    stateButton.setPadding(0, 0, 0, 0);
                    stateButton.setLayoutParams(new ViewGroup.MarginLayoutParams(mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp80), mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp29)));
                    stateButton.setNormalBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                    stateButton.setPressedBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                    stateButton.setText(listBean.getValue());
                    stateButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
                    stateButton.setTextColor(mActivity.getResources().getColor(R.color.common_color_c3_ffffff));
                    mEndNewLineLayout.addView(stateButton);
                }

                StateButton resetBtn = new StateButton(mActivity);
                resetBtn.setRound(true);
                resetBtn.setPadding(0, 0, 0, 0);
                ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp80), mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp29));
                resetBtn.setNormalStrokeColor(mActivity.getResources().getColor(R.color.common_color_c2_f7a82f));
                resetBtn.setPressedStrokeColor(mActivity.getResources().getColor(R.color.common_color_c2_f7a82f));
                resetBtn.setNormalStrokeWidth(mActivity.getResources().getDimensionPixelOffset(R.dimen.common_dimen_dp_half));
                resetBtn.setPressedStrokeWidth(mActivity.getResources().getDimensionPixelOffset(R.dimen.common_dimen_dp_half));
                resetBtn.setText("重置");
                resetBtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
                resetBtn.setTextColor(mActivity.getResources().getColor(R.color.common_color_c2_f7a82f));
                params.leftMargin = ConvertUtils.dip2px(mActivity, 15);
                mEndNewLineLayout.addView(resetBtn, params);

                resetBtn.setId(R.id.btn_reset_end);
                resetBtn.setOnClickListener(ChangeTypeParentPositionFragment.this);
            } else {
                mEndNewLineLayout.removeAllViews();

                mEndImg.setVisibility(View.GONE);
                mEndDetailsLayout.setVisibility(View.VISIBLE);

                for (DimensionBean.EndBean.ListBean listBean : dimensionBean.getEnd().getList()) {
                    TextView textView = new TextView(mActivity);
                    textView.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT));
                    textView.setText(listBean.getValue() + " ");
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
                    textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                    mEndNewLineLayout.addView(textView);
                }
            }
        }

        if (TaskCenterCommon.getInstance().getEndMap() != null && TaskCenterCommon.getInstance().parseEndMap().size() > 0) {
            mSaveLayout.setVisibility(View.VISIBLE);
        } else {
            mSaveLayout.setVisibility(View.GONE);
        }
    }

    private class ChangeTypeParentPositionReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if ("ChooseAddWayParentPositionByAny".equals(action)) {
                if (TaskCenterCommon.getInstance().isStart()) {

                } else {
                    mEndNewLineLayout.removeAllViews();

                    mEndImg.setVisibility(View.GONE);
                    mEndDetailsLayout.setVisibility(View.GONE);

                    StateButton anyBtn = new StateButton(mActivity);
                    anyBtn.setRound(true);
                    anyBtn.setPadding(0, 0, 0, 0);
                    anyBtn.setLayoutParams(new ViewGroup.MarginLayoutParams(mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp80), mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp29)));
                    anyBtn.setNormalBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                    anyBtn.setPressedBackgroundColor(mActivity.getResources().getColor(R.color.common_color_c1_337cff));
                    anyBtn.setText("任意");
                    anyBtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
                    anyBtn.setTextColor(mActivity.getResources().getColor(R.color.common_color_c3_ffffff));
                    mEndNewLineLayout.addView(anyBtn);

                    StateButton resetBtn = new StateButton(mActivity);
                    resetBtn.setRound(true);
                    resetBtn.setPadding(0, 0, 0, 0);
                    ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp80), mActivity.getResources().getDimensionPixelSize(R.dimen.common_dimen_dp29));
                    resetBtn.setNormalStrokeColor(mActivity.getResources().getColor(R.color.common_color_c2_f7a82f));
                    resetBtn.setPressedStrokeColor(mActivity.getResources().getColor(R.color.common_color_c2_f7a82f));
                    resetBtn.setNormalStrokeWidth(mActivity.getResources().getDimensionPixelOffset(R.dimen.common_dimen_dp_half));
                    resetBtn.setPressedStrokeWidth(mActivity.getResources().getDimensionPixelOffset(R.dimen.common_dimen_dp_half));
                    resetBtn.setText("重置");
                    resetBtn.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
                    resetBtn.setTextColor(mActivity.getResources().getColor(R.color.common_color_c2_f7a82f));
                    params.leftMargin = ConvertUtils.dip2px(mActivity, 15);
                    mEndNewLineLayout.addView(resetBtn, params);

                    resetBtn.setId(R.id.btn_reset_end);
                    resetBtn.setOnClickListener(ChangeTypeParentPositionFragment.this);
                }
            } else if ("ChooseAddWayParentPositionByWarehousePoint".equals(action)) {   //仓库点
                if (TaskCenterCommon.getInstance().isStart()) {

                } else {
                    mEndNewLineLayout.removeAllViews();

                    if (TaskCenterCommon.getInstance().parseEndMap().size() > 0) {
                        mEndImg.setVisibility(View.GONE);
                        mEndDetailsLayout.setVisibility(View.VISIBLE);

                        for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseEndMap()) {
                            TextView textView = new TextView(mActivity);
                            textView.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT));
                            textView.setText(taskCenterBean.getValue() + " ");
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
                            textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                            mEndNewLineLayout.addView(textView);
                        }
                    } else {
                        mEndImg.setVisibility(View.VISIBLE);
                        mEndDetailsLayout.setVisibility(View.GONE);
                    }
                }
            }

            if (TaskCenterCommon.getInstance().getEndMap() != null && TaskCenterCommon.getInstance().parseEndMap().size() > 0) {
                mSaveLayout.setVisibility(View.VISIBLE);
            } else {
                mSaveLayout.setVisibility(View.GONE);
            }
        }
    }

    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_SAVE_DIMENSION:
                    if ("0".equals(commonClass.getCode())) {
                        // 保存成功, 父作业点位置维度选中
                        popFragment();

                        Intent intent = new Intent("ChangeTypeDimension");
                        mActivity.sendBroadcast(intent);
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {
            toast(s);
        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
}
